import { Singleton } from '../../framework/common/Singleton';
import { Npc } from '../entity/npc/npc';
import npcData from '../json/npc/npc_1.json';

/**
 * NPC管理器 / NPC Manager
 */
export class NpcMgr extends Singleton<NpcMgr>() {
    private _npcMap: Map<string, Npc> = new Map();
    constructor() {
        super();
        console.log('(Server) NpcMgr constructor');
    }

    /**
     * 启动 / Start
     * @param id 地图ID / Map ID
     */
    public start(id: number | string): void {
        if (id === 'main') {
            npcData.ids.forEach((npcId) => {
                this.addNpcById(npcId);
            });
        }
    }

    /**
     * 添加NPC / Add NPC
     * @param id NPC ID / NPC ID
     * @param npc NPC / NPC
     */
    public addNpc(id: string, npc: Npc) {
        this._npcMap.set(id, npc);
    }

    public addNpcById(id: string) {
        const npcConfig = npcData.configs[id as keyof typeof npcData.configs];
        const npc = new Npc();
        const entities = world.querySelectorAll(`#${id}`);
        entities.forEach((entity) => {
            npc.start({ ...npcConfig, entity });
            this._npcMap.set(id, npc);
        });
    }
}
